package utils;
import business.Constants;
import models.files;
import play.Logger;
import play.db.jpa.Blob;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件操作
 */
public class FileUtil {
	/**
	 * 上传文件
	 */
	public static Map<String, Object> uploadFile(File file, ErrorInfo error) {
		error.clear();
		if (null == file) {
			error.code = -1;
			error.msg = "上传文件为空";
			return null;
		}
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			Logger.error(e.getMessage());
			error.code = -4;
			error.msg = "找不到文件"+file.getName();
			return null;
		}
		Blob blob = new Blob();
		blob.set(fis, "");
		String fileName = file.getName();
		String fileExt = fileName.substring(fileName.lastIndexOf(".")+1);
		Map<String, Object> fileInfo = new HashMap<String,Object>();
		String uuid = blob.getUUID();
		fileInfo.put("size", Arith.div(file.length(), 1024, 2));
		fileInfo.put("filename",uuid);
		fileInfo.put("filetype",fileExt );
		fileInfo.put("file_realname",fileName);
		return fileInfo;
	}
	public static void deleteFile(String filename){
		String abspath = Constants.getAbsPath(filename);
		Logger.info("delete-xls:" + abspath);
		new File(abspath).delete();// 删除空文件夹
		files.delete("from files where filename=?",filename) ;
	}
}
